package com.example.myapp

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapp.databinding.ActivityRecycleviewBinding

/**
 * @author weng
 * @date 2022/8/5 15:32
 * @describe
 */
class RecycleViewActivity : AppCompatActivity() {
    private var  activityRecycleviewBinding: ActivityRecycleviewBinding?=null
    private var data:ArrayList<String>? =null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        activityRecycleviewBinding= ActivityRecycleviewBinding.inflate(layoutInflater)
        setContentView(activityRecycleviewBinding?.root)
        initData()

        val myAdapter = data?.let { MyAdapter(it) }
        activityRecycleviewBinding?.recycleView?.layoutManager = LinearLayoutManager(this,RecyclerView.VERTICAL,false)
        activityRecycleviewBinding?.recycleView?.adapter = myAdapter
        myAdapter?.notifyDataSetChanged()


    }

     fun  initData(){
        for (index in 0 until 50){
            data?.add("i-->$index")
        }

    }
   class MyAdapter(var newsList:List<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
        //在内部类里面获取到item里面的组件
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            var textView: TextView = view.findViewById(R.id.tv_text)
        }

        //重写的第一个方法，用来给制定加载那个类型的Recycler布局
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_text, parent, false)
            var viewHolder = ViewHolder(view)


            return viewHolder
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val news = newsList[position]
            holder.textView.text= news
        }

        override fun getItemCount(): Int {
            return newsList.size
        }
    }
}